<?php
namespace hema\device\engine;


/**
 * 大趋智能云打印机驱动模块
 * 测试机型号：P7
 */
class Daqu extends Basics
{
    /**
     * 构造方法
     */
    public function __construct($dev_type, $device, $data, $tpl)
    {
        parent::__construct($dev_type, $device, $data, $tpl);
    }
    
    /**
    * 打印订单接口
    */
    public function print()
    {
        if($this->tpl==0){
            //打印类目筛选 ,参数存在 说明已经配置
            if(isset($this->device['values']['category'])){
                $goods = [];//筛选后的商品目录
                //循环订单商品
                for ($n = 0; $n < sizeof($this->data['goods']); $n++) {
                    foreach ($this->device['values']['category'] as $item) {
                        //判断是否在打印类目中
                        if($this->data['goods'][$n]['goods']['category_id'] == $item){
                            $goods[] = $this->data['goods'][$n];
                        }
                    }
                }
                if(sizeof($goods) == 0){
                    //没有要打印的内容
                    return true;
                }else{
                    //更新打印商品列表
                    $this->data['goods'] = $goods;
                }
            }
            $content = $this->make_order_templet($this->data);//制作订单模板
            $voice = '10';
        }else{
            $content = $this->make_refund_templet($this->data);//制作退单模板
            $voice = '11';
        }
        $params = [
            "sn" => $this->device['dev_id'],//打印机终端号
            "voice" => $voice, //语音内容
            "content" => $content,//打印内容
            "copies" => (int)$this->device['values']['prt_num']     //打印分数

        ];
        $result = json_decode($this->http_post_json('print','POST',$params,true),true);
        sleep(1);//延时1秒
        if($result['code'] != 0){
            $this->error = $result['message'];
            return false;
        }
        return $result;
    }
    
    /**
    * 授权绑定打印机
    */
    public function add()
    {
        $data = $this->data;
        $params = [
            [
                "sn" =>  $data['dev_id'],//打印机终端号
                "key"=> $data['dev_key'],//打印机终端密钥
                "name"=>$data['dev_name'],//自定义打印机名称(可填)
            ]
        ];
        $result = json_decode($this->http_post_json('addPrinter','POST',$params,true),true);
        if($result['code'] != 0){
            $this->error = $result['message'];
            return false;
        }
        if(isset($result['data']['fail'][0]['reason'])){
            $this->error = $result['data']['fail'][0]['reason'];
            return false;
        }
        return $result;
    }
    
    /**
    * 删除授权绑定的打印机
    */
    public function delete()
    {
        $params = [$this->data['dev_id']];
        $result = json_decode($this->http_post_json('delPrinter','POST',$params,true),true);
        if($result['code'] != 0){
            $this->error = $result['message'];
            return false;
        }
        if(isset($result['data']['fail'][0]['reason'])){
            $this->error = $result['data']['fail'][0]['reason'];
            return false;
        }
        return $result;
    }
    
    /**
    * 获取打印机状态接口 
    */
    public function status()
    {
        $params = [
            "sn" =>  $this->data['dev_id'],//打印机终端号
        ];
        $result = json_decode($this->http_post_json('getDeviceStatus','POST',$params,true),true);
        sleep(1);//延时1秒
        if($result['code'] != 0){
            return '未知';
        }
        if($result['data']['onlineStatus'] == 1){
            if($result['data']['workStatus'] == 0){
                return '正常';
            }
            return $result['data']['workStatusDesc'];
        }
        return '离线';
    }

    /**
    * 获取Token
    */
    public function getToken()
    {
        
    }

    public function edit()
    {
        
    }
    public function push()
    {
        
    }

    // 请求工具方法
    public function http_post_json($url, $method = 'GET', $postfields = null, $debug = false) {
        $url = $this->config['api_url'] . '/openapi/' . $url;
        $headers = $this->getHeader($postfields); 
        $body = hema_json($postfields);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers); // 设置通用传参
        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $body);
                }
                break;
        }

        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);// 从证书中检查SSL加密算法是否存在
        curl_setopt($ci, CURLOPT_URL, $url);
        $response = curl_exec($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        $request_header = curl_getinfo($ci, CURLINFO_HEADER_OUT);
        curl_close($ci);
        return $response;
    }
    
    // Header通用参数
    private function getHeader($data)
    {
        $body = hema_json($data);
        $timestamp = time();
        $uid = md5($timestamp);
        $sign = md5($uid . $this->config['app_key'] . $timestamp . $this->config['app_secret'] . $body);
        $header = array();
        $header[] = "Content-Type:application/json";
        $header[] = "appid:" . $this->config['app_key'];
        $header[] = "uid:" . $uid;
        $header[] = "stime:" . $timestamp;
        $header[] = "sign:" . $sign;
        return $header;
        
        
    }

    /**
     * 制作订单模板
     * $data 订单数据
     * $n 打印份数
     * 58mm的机器,一行打印16个汉字,32个字母;
     */
    private function make_order_templet($data)
    {
        if($data['order_mode']['value']==10){
            if(isset($data['table']['table_name'])){
                $title = $data['table']['table_name'];
            }else{
                $title = '堂食'.$data['row_no'].'号';
            }
        }
        if($data['order_mode']['value']==20){
            $title = '外卖'.$data['row_no'].'号';
        }
        if($data['order_mode']['value']==30){
            $title = '自取'.$data['row_no'].'号';
        }
        
        /*
        <BR>              换行符
        <C></C>           居中
        <LEFT></LEFT>     左对齐
        <RIGHT></RIGHT>   右对齐
        <QR></QR>         二维码内容，字符个数范围：<=128个字节
        <BAR></BAR>       条形码，编码方式：CODE 128B字体，字符个数范围: n < 15
        <font# bolder="" height="" width=""></font#>   字体大小设置，bolder是否加粗[0 普通 1 加粗]  height倍高[取值1-8] width倍宽[取值1-8]
        */
        $content = "<C><font# bolder=1 height=2 width=2># " . $title . " #</font#></C><BR>";
        if($data['arrive_time']['value']>0){
            $content .= "到店时间:" . $data['arrive_time']['text'] . "<BR>";
        }
        $content .= str_repeat('-', 32);
        $content .= "<BR>";
        $content .= "<C>".$data['shop']['shop_name']."</C><BR>";
        if($data['pay_status']['value'] != 30){
            if($data['transaction_id']){
                $content .= "<C>-- 微信支付 --</C><BR>";
            }else{
                $content .= "<C>-- 余额支付 --</C><BR>";
            }
            $content .= "支付时间：".datetime($data['pay_time'])."<BR>";
        }else{
            $content .= "<C>-- 后付款 --</C><BR>";
        }
        $content .= "<font# bolder=1 height=2 width=2>名称        数量</font#><BR>";//16=4+8+4
        $content .= str_repeat('-', 32);
        $content .= "<BR>";
        //循环拼接打印模板
        for ($i = 0; $i < sizeof($data['goods']); $i++) {
                $goods_name = $data['goods'][$i]['goods_name'];//产品名字
                !empty($data['goods'][$i]['goods_attr']) && $goods_name .= "/" . $data['goods'][$i]['goods_attr'];
                $total_num = $data['goods'][$i]['total_num'];   //产品数量
                //设置名称字符长度
                $lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
                for($n=$lan;$n<13;$n++){
                    $goods_name .= ' ';
                }
                $content .= "<font# bolder=1 height=2 width=2>" . $goods_name . "×" . $total_num."</font#><BR>";
        }
        $content .= str_repeat('-', 32);
        $content .= "<BR>";
        $content .= "商品金额：+￥".$data['total_price']."<BR>";
        if($data['express_price']>0){
            $content .= "配送费用：+￥".$data['express_price']."<BR>";
        }
        if($data['pack_price']>0){
            $content .= "餐盒费用：+￥".$data['pack_price']."<BR>";
        }
        if($data['ware_price']>0){
            $content .= "餐具调料：+￥".$data['ware_price']."<BR>";
        }
        if($data['activity_price']>0){
            $content .= "优惠金额：-￥".$data['activity_price']."<BR>";
        }
        $content .= "实付金额：￥".$data['pay_price']."<BR>";
        if($data['flavor']){
            $content .= "口味要求：".$data['flavor']."<BR>";
        }
        if($data['message']){
            $content .= "顾客留言：".$data['message']."<BR>";
        }
        if($data['order_mode']['value']==20){
            $content .= "配送地址：".$data['address']['detail']."<BR>";
            $content .= "接 收 人：".$data['address']['name'].$data['address']['phone']."<BR>";
        }
        $content .= "<C><font# bolder=1 height=2 width=2># " . $title . " # 完</font#></C><BR>";
        return $content;
    }
    
    /**
     * 制作退单模板
     * $data 退单数据
     * $n 打印份数
     * 58mm的机器,一行打印16个汉字,32个字母;
     */
    private function make_refund_templet($data,$n)
    {
        if($data['order_mode']['value']==10){
            if(isset($data['table']['table_name'])){
                $title = $data['table']['table_name'];
            }else{
                $title = '堂食'.$data['row_no'].'号';
            }
        }
        if($data['order_mode']['value']==20){
            $title = '外卖'.$data['row_no'].'号';
        }
        if($data['order_mode']['value']==30){
            $title = '自取'.$data['row_no'].'号';
        }
        $content = "<C><font# bolder=1 height=2 width=2># 退单- 开始 #</font#></C><BR>";
        $content .= "<C><font# bolder=1 height=2 width=2># " . $title . " #</font#></C><BR>";
        $content .= str_repeat('-', 32);
        $content .= "<BR><C>".$data['shop']['shop_name']."</C><BR>";
        $content .= "<font# bolder=1 height=2 width=2>名称        数量</font#><BR>";//16=4+8+4
        $content .= str_repeat('-', 32);
        $content .= "<BR>";
        //循环拼接打印模板
        for($i = 0; $i < sizeof($data['goods']); $i++) {
            if($data['goods'][$i]['refund_num']>0){
                $goods_name = $data['goods'][$i]['goods_name'];//产品名字
                !empty($data['goods'][$i]['goods_attr']) && $goods_name .= "/" . $data['goods'][$i]['goods_attr'];
                $refund_num = $data['goods'][$i]['refund_num']; //产品数量
                //设置名称字符长度
                $lan = mb_strlen($goods_name,'utf-8')*2;//一个汉字2个字符长度
                for($n=$lan;$n<13;$n++){
                    $goods_name .= ' ';
                }
                $content .= "<font# bolder=1 height=2 width=2>" . $goods_name . "×" . $refund_num."</font#><BR>";
            }
        }
        $content .= str_repeat('-', 32);
        $content .= "<BR>";
        $content .= "支付金额：￥".$data['pay_price']."<BR>";
        $content .= "退款金额：￥".$data['refund_price']."<BR>";
        $content .= "退款理由：".$data['refund_desc']."<BR>";
        $content .= "<C><font# bolder=1 height=2 width=2># 退款 # 完</font#></C><BR><BR>";
        return $content;
    }

}
